﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Whir.Common;
using Whir.Common.WebHelper;
using System.IO;

public partial class Whir_System_Module_Config_BakDatabase : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        RoleHelper.IsLogin();    //登录判断
        if (!IsPostBack)
        {
            BindData();
        }
    }

    private void BindData()
    {
        DataTable dt = FileSystemObject.GetDirectoryInfos(Server.MapPath("~/Temp/DBbak/"), FsoMethod.File);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string fileName = TextBox1.Text;

        if (string.IsNullOrEmpty(fileName))
        {
            JsHelper.Alert(Page, "请输入数据库备份的名称！");
            return;
        }

        if (File.Exists(Server.MapPath("~/Temp/DBbak/") + fileName + ".BAK"))
        {
            JsHelper.Alert(Page, "以【" + fileName + "】命名的备份文件已经存在，请重新输入！");
            TextBox1.Text = "";
            TextBox1.Focus();
            return;
        }

        bool flag = false;
        flag = DBBackUpHelper.DbBackup(Page, fileName);
        if (flag)
            JsHelper.Alert("备份成功！");
        else
            JsHelper.Alert("备份失败！");

        BindData();
    }

    protected void Button2_Click(object sender, EventArgs e)
    {

    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Down")
        {
            DowFile(this.Page.Server.MapPath("~/Temp/DBbak/") + e.CommandArgument.ToString(), e.CommandArgument.ToString());
        }
        else if (e.CommandName == "DeleteItem")
        {
            FileSystemObject.DeleteFile(Server.MapPath("~/Temp/DBbak/") + e.CommandArgument);
            JsHelper.Alert(Page, "数据库备份删除成功！");
        }
        BindData();
    }

    public void DowFile(string filePath, string fileName)
    {
        try
        {
            FileInfo fi = new FileInfo(filePath);

            HttpContext.Current.Response.Clear();

            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fi.Name));
            HttpContext.Current.Response.AddHeader("Content-Length", fi.Length.ToString());
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.WriteFile(fi.FullName);
            HttpContext.Current.Response.End();
        }
        catch
        {
            JsHelper.Alert(this.Page, "对不起，此文件已经删除！");
            return;
        }
    }
}